<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/9/28
 * Time: 11:04
 */

namespace app\admin\controller;


use app\admin\model\ApiResponse;
use app\admin\lib\AdminController;
use app\api\model\user\Users;
use app\api\model\curriculum\Curriculum as Curri;
use app\common\model\BuyBill;
use OSS\OssClient;
use think\Db;
use think\Exception;
use think\Log;
use think\Request;

class Bills extends AdminController
{
    private function getList($export) {

        $form = $this->getAndCheckForm([
            ['rows', 'integer',],
            ['page', 'integer',],
            ['have_paid', 'integer',],
            ['start', 'date',],
            ['end', 'date',],
        ]);

        $start = empty($form['start']) ? 0 : strtotime($form['start']);
        $end = empty($form['end']) ? time() : strtotime($form['end']);
        if ($start>0 && $end>0 && $start>=$end) ApiResponse::error(ApiResponse::ERR_FORM_INVALID,'时间范围不正确');

        $re = BuyBill::manageList($form['rows']??10,$form['page']??1,$form['have_paid']??-1,
            $start, $end,$export,$form['no']??null,$form['mobile']??null,$form['type']??0,
            $form['pay']??0);

        return $re;
    }
    /**
     * 订单列表用于查看
     *
     * @return array
     */
    public function list() {

        $re = $this->getList(false);

        $re['code'] = 200;
        return $re;
    }

    /**
     * 导出订单的数据表
     * 输出Excel文件
     */
    public function list_export_excel() {

        $re = $this->getList(true);

        $form = $this->getAndCheckForm();
        $start = empty($form['start']) ? 0 : strtotime($form['start']);
        $end = empty($form['end']) ? time() : strtotime($form['end']);

        $filename = '订单导出'.date('Y-m-d', $start).'-'.date('Y-m-d', $end);
        $excel = new \PHPExcel();
        $sheet = $excel->setActiveSheetIndex(0);
        $sheet->setTitle($filename);
        $sheet->setCellValue('A1', 'ID');
        $sheet->setCellValue('B1', '商品');
        $sheet->setCellValue('C1', '订单号');
        $sheet->setCellValue('D1', '支付金额');
        $sheet->setCellValue('E1', '时间');
        $sheet->setCellValue('F1', '支付方式');
        $sheet->setCellValue('G1', '用户手机号');

        foreach ($re as $k => $v) {
            $k = $k + 2;
            $sheet->setCellValue('A'.$k, (string)$v['bill_id']);
            $sheet->setCellValue('B'.$k, (string)$v['bill_item_title']);
            $sheet->setCellValue('C'.$k, (string)$v['bill_no']);
            $sheet->setCellValue('D'.$k, (string)$v['bill_pay_amount']);
            $sheet->setCellValue('E'.$k, (string)$v['bill_createtime']);
            $sheet->setCellValue('F'.$k, (string)$v['bill_pay_method']);
            $sheet->setCellValue('G'.$k, (string)$v['mobile']);
        }

        header("Content-type: application/octet-stream;");
        header("Content-Disposition: attachment; filename={$filename}.xls");
        $writer = new \PHPExcel_Writer_Excel5($excel);
        $writer->save('php://output');
    }

    /**
     * 确认支付成功后，设置订单为成功，并自动做后续处理
     *
     * @return ApiResponse
     */
    public function exec_success() {
        $form = $this->getAndCheckForm([
            ['bill_id', 'require|integer',],
        ]);

        $bill = BuyBill::get($form['bill_id']);
        if ($bill->bill_have_paid)
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'已经支付成功，无需处理');

        if ($bill->chkBought()) {
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'重复的购买订单，可能是无效的或数据重复');
        }

        $re = $bill->successPay();
        if ($re) return ApiResponse::success();
        else return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'操作失败了，可能订单数据错误');
    }

    /**
     * 直接创建订单，状态为成功，为线下交易提供接口
     */
    public function create() {
        $form = $this->getAndCheckForm([
            ['mobile', 'require|^[1][3,4,5,7,8][0-9]{9}$','无效手机号',],
            ['item_type', 'require|integer|between:1,3',],
            ['item_id', 'require|integer|min:1',],
            ['bill_type', 'require|integer|between:1,4',],
            ['pay_method', 'require|integer|between:0,4',],
            ['pay_amount', 'require|float',],
            ['pay_time', 'integer|min:0',],
            ['has_paid', 'integer|between:0,1',],
        ]);
        $has_paid = (true == ($form['has_paid']??false));

        try{
            Db::startTrans();

            $user = Users::addUserIfNonExists($form['mobile'],'NOT-ACTIVE',$form['realname']??null,
                $form['nickname']??null,Users::REGISTER_FROM_ADMIN);

            if (BuyBill::BILL_TYPE_GIFT == $form['bill_type']) {
                $form['pay_method'] = 0;
                $form['pay_amount'] = '0.00';
                $form['pay_trade_no'] = '';
            }

            $bill = BuyBill::addBill($user->id, $form['item_type'], $form['item_id'], $form['pay_method'],
                $form['pay_amount'], $form['pay_trade_no']??'', $form['pay_time'], $form['bill_type']);

            if ($has_paid) {
                $bill->successPay();
            }

            Db::commit();

            return ApiResponse::success($bill);
        }catch (Exception $ex){
            Db::rollback();
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED, $ex->getMessage());
        }
    }

    public function curriculum_names() {
        // zk 20180524 获取可绑定文章的课程的文章栏目id
        $form = $this->getAndCheckForm();
        $form['bindArticleColId'] = $form['bindArticleColId']??0;

        $list = Curri::namesForBill($form['bindArticleColId']);
        return ApiResponse::success($list);
    }

    public function delete() {
        $form = $this->getAndCheckForm([
            ['id','require|integer|min:1'],
        ]);

        $bill = BuyBill::get($form['id']);
        if (empty($bill)) return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'订单不存在');
        if ($bill->bill_have_paid) return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'订单已经完成，不能删除');

        $bill->delete();

        return ApiResponse::success();
    }

    public function statistic() {
        $form = $this->getAndCheckForm([
            ['start','date',],
            ['end','date',],
        ]);

        $start = isset($form['start']) ? strtotime($form['start']) : 0;
        $end = isset($form['end']) ? strtotime($form['end']) : 0;

        $result = BuyBill::sumByItem($start, $end);

        return ApiResponse::success($result);
    }

}